package localCache

import (
	"testing"
	"time"
)

type CacheItem struct {
	Key       string
	Value     interface{}
	ExpiresAt time.Time
}

type Cache struct {
	items map[string]CacheItem
}

func NewCache() *Cache {
	c := &Cache{
		items: make(map[string]CacheItem),
	}
	go c.startCleanup()
	return c
}

func (c *Cache) Set(key string, value interface{}, expiration time.Duration) {
	c.items[key] = CacheItem{
		Key:       key,
		Value:     value,
		ExpiresAt: time.Now().Add(expiration),
	}
}

func (c *Cache) Get(key string) (interface{}, bool) {
	item, found := c.items[key]
	if !found {
		return nil, false
	}
	if time.Now().After(item.ExpiresAt) {
		delete(c.items, key)
		return nil, false
	}
	return item.Value, true
}

func (c *Cache) Del(key string) bool {
	delete(c.items, key)
	return true
}

func (c *Cache) startCleanup() {
	for {
		time.Sleep(1 * time.Minute)
		for key, item := range c.items {
			if time.Now().After(item.ExpiresAt) {
				delete(c.items, key)
			}
		}
	}
}

func TestAdd(t *testing.T) {
	cache := NewCache()
	cache.Set("key1", "value1", 5*time.Second)
	cache.Set("key2", "value2", 10*time.Second)

	for {
		if value, ok := cache.Get("key1"); ok {
			println(value.(string))
		} else {
			println("key1 not found")
		}

		if value, ok := cache.Get("key2"); ok {
			println(value.(string))
		} else {
			println("key2 not found")
		}

		time.Sleep(1 * time.Second)
	}
}
